package org.jiajin2coding.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jiajin2coding.reggie.common.ResultVO;
import org.jiajin2coding.reggie.entity.Employee;
import org.jiajin2coding.reggie.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author Guo Jinhua (jiajin2coding)
 * @version 1.0.0
 * @className EmployeeController
 * @description
 * @date 2023-10-24
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    private static final String INIT_PASSWORD = "123456";

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public ResultVO<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        /**
         * 登录业务处理逻辑
         * 1. 将页面提交的密码 password 进行 MD5 加密处理
         * 2. 根据页面提交的用户名 username 查询数据库
         * 3. 如果没有查询到则返回登录失败结果
         * 4. 密码对比：如果不一致则返回登录失败结果
         * 5. 查看员工状态，如果为已禁用，则返回员工已禁用结果
         * 6. 登陆成功，将员工 id 存入 session 并返回登录成功结果
         */
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee oneEmp = employeeService.getOne(queryWrapper);

        if (oneEmp == null || ObjectUtils.isEmpty(oneEmp)) {
            return ResultVO.error("查询用户信息为空，登录失败！");
        }

        if (!oneEmp.getPassword().equals(password)) {
            return ResultVO.error("输入用户名或密码不正确，登录失败！");
        }

        if (oneEmp.getStatus() == 0) {
            return ResultVO.error("用户账号信息已禁用，登录失败！");
        }

        request.getSession().setAttribute("employee", oneEmp.getId());

        return ResultVO.success(oneEmp);
    }

    /**
     * 推出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public ResultVO<String> logout(HttpServletRequest request) {
        // 1. 清除 session 中的用户ID
        request.getSession().removeAttribute("employee");
        // 2. 返回结果
        return ResultVO.success("退出成功");
    }

    /**
     * 员工信息保存
     * @param employee
     * @return
     */
    @PostMapping("/save")
    public ResultVO<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工: 员工信息 {}", employee.toString());
        Employee employeeInfo = employeeService.queryEmployeeInfoByName(employee.getUsername());
        if (!ObjectUtils.isEmpty(employeeInfo) && employee != null) {
            log.info("根据用户名获取用户信息 {}", employeeInfo.toString());
            return ResultVO.error("5001",
                    String.format("用户信息已存在, 用户名 %s, 姓名 %s", employee.getUsername(), employee.getName()));
        }
        // 设置初始密码：12345 同时对密码进行加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex(INIT_PASSWORD.getBytes()));
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        // 获取当前登录用户ID
        Long empId = (Long) request.getSession().getAttribute("employee");
        Employee loginEmp = employeeService.getById(empId);
        log.info("当前登录用户的信息 {}", loginEmp.toString());
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        employeeService.save(employee);
        return ResultVO.success("新增员工信息成功");
    }

    /**
     * 分页查询员工信息：不显示管理员
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public ResultVO<Page> getEmployeeByPage(int page, int pageSize, String name) {
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        /*queryWrapper.ne(Employee::getUsername, "admin");
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name)
                .or()
                .like(StringUtils.isNotEmpty(name), Employee::getUsername, name);*/
        // queryWrapper.ne(Employee::getUsername, "admin")
        queryWrapper.notIn(Employee::getUsername, new String[]{"admin"})
                .and(StringUtils.isNotEmpty(name), wrapper ->
                        wrapper.like(Employee::getName, name)
                                .or()
                                .like(Employee::getUsername, name));
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo, queryWrapper);
        return ResultVO.success(pageInfo);
    }

    /**
     * 修改员工信息
     * @param employee
     * @return
     */
    @PutMapping("/edit")
    public ResultVO<String> editEmpInfo(HttpServletRequest request, @RequestBody Employee employee) {
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());
        employeeService.updateById(employee);
        return ResultVO.success("员工信息更新成功");
    }

    /**
     * 根据ID查询员工信息
     * @param empId
     * @return
     */
    @GetMapping("/queryEmpInfoById/{empId}")
    public ResultVO<Employee> queryEmpInfoById(@PathVariable("empId") Long empId) {
        Employee employee = employeeService.getById(empId);
        return ResultVO.success(employee);
    }

}
